package com.xinchen.gufeiwulian.vm

import com.blankj.utilcode.util.GsonUtils
import com.maple.model.data.AppUserInfo
import com.maple.model.entity.xc.LoginEntity
import com.maple.model.entity.xc.LoginEntity.AppUser
import com.maple.utils.manager.SingleLiveEvent
import com.maple.utils.store.AppDBHelper
import com.maple.utils.util.HttpRequestUtils
import com.maple.utils.util.LogUtils
import com.xinchen.gufeiwulian.base.BaseViewModel
import com.xinchen.gufeiwulian.model.repository.CommonRepository
import java.util.WeakHashMap

class AccountViewModel: BaseViewModel(){

    private val repository by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) { CommonRepository() }

    val loginEvent: SingleLiveEvent<Any> = SingleLiveEvent()

    var isDebugModel: Boolean = false

    fun onLogin(account: String,password: String,isRememberPwd: Boolean,platform: Int,user: WeakHashMap<String, Any>) {
        HttpRequestUtils.clearAccessToken()
        launchOnlyResult(block = {
            val params: WeakHashMap<String, Any> = WeakHashMap()
            params.put("user", user)
            repository.login(params)
        }, success = {
            it.let { data ->
                val entity = GsonUtils.fromJson(GsonUtils.toJson(data), LoginEntity::class.java)
                entity?.appUser?.let { user ->
                    LogUtils.logGGQ("==token==>>>${user.token}")
//                    HttpRequestUtils.putAccessToken(it.token)
                    saveUserInfo(account,password,isRememberPwd,platform,user)
                }?:let {
                    LogUtils.logGGQ("==获取appUser数据为空！！！===>>>")
                    defUI.onToast("登录失败！")
                }
            }
        })
    }

    private fun saveUserInfo(account: String,password: String,isRememberPwd: Boolean,platform: Int,user: AppUser) {

        val userInfo: AppUserInfo = AppUserInfo()
        userInfo.token = user.token?:""
        userInfo.userName = user.userName?:""
        userInfo.roleName = user.roleName?:""
        userInfo.realName = user.realName?:""
        userInfo.userId = user.userId?:""
        userInfo.enterpriseId = user.enterpriseId?:""
        userInfo.enterpriseName = user.enterpriseName?:""
        userInfo.weightManualInput = user.weightManualInput?:false
        userInfo.shouDong = user.shouDong?:false
        userInfo.isDF = user.isDF?:""
        userInfo.orgId = user.orgId?:""
        userInfo.orgSort = user.orgSort?:""
        userInfo.orgType = user.orgType?:""
        userInfo.enterpriseCategory = user.enterpriseCategory?:""
        userInfo.isDengJi = user.isDengJi?:""
        userInfo.isShouJi = user.isShouJi?:""
        AppDBHelper.saveLoginInfo(account,if(isRememberPwd) password else "",platform)
        if(AppDBHelper.saveUser(userInfo)) {
            loginEvent.call()
        } else {
            defUI.onToast("登录失败！")
        }
    }
}